const cart = require('../../services/cart.js');
const order = require('../../services/order.js');
//获取应用实例
const app = getApp()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog.js';

const user = require('../../services/user.js');
const util = require('../../utils/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        list: [],
        selectList: [],
        login: false,
        userInfo: {},
        total: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            login: wx.getStorageSync("login") === '' ? false : wx.getStorageSync("login"),
            selectList: wx.getStorageSync("selectList") === '' ? [] : wx.getStorageSync("selectList")
        })
    },

    subOrder() {
        const ids = this.data.selectList
        if (ids.length < 1) {
            wx.showModal({
                title: '请选择要支付的商品',
                showCancel: false
            })
            return;
        }
        wx.showLoading({
            title: '提交中',
            mask: true
        })
        const data = {
            cartId: this.data.selectList
        }
        order.add(data, (res) => {
            if (res.code === 0) {
                this.setData({
                    selectList: []
                })
                wx.setStorageSync("selectList", [])
                wx.navigateTo({
                    url: '../order/order?id=' + res.msg
                })
            }
        })
        wx.hideLoading()
    },

    getList() {
        cart.list({}, (res) => {
            if (res.code === 0) {
                let selectList = this.data.selectList
                let list = res.data
                for (let i in list) {
                    for (let j in selectList) {
                        if (selectList[j] === list[i].id) {
                            list[i]['ck'] = true
                        }
                    }
                }
                this.setData({
                    list: list
                })
                this.sumPrice(list, selectList)
            }
        })
    },

    sumPrice(list, selectList) {
        let price = 0;
        selectList.forEach(function (item, index, array) {
            for (const i in list) {
                if (item === list[i].id) {
                    const p = util.mul(list[i].commodity.price, list[i].number)
                    price = util.add(price, p);
                }
            }
        })
        this.setData({
            total: price
        })
    },

    onChange(event) {
        let selectList = this.data.selectList
        const index = event.currentTarget.dataset.index
        let list = this.data.list
        const r = list[index].ck
        list[index].ck = !r
        if (list[index].ck) {
            selectList.push(list[index].id)
        } else {
            selectList.forEach(function (item, i, array) {
                if (item === list[index].id) {
                    array.splice(i, 1)
                }
            })
        }
        this.setData({
            list: list,
            selectList: selectList
        })
        wx.setStorageSync("selectList", selectList)
        this.sumPrice(list, selectList)
    },

    onClose(event) {
        const {position, instance} = event.detail;
        if (position === 'right') {
            Dialog.confirm({
                message: '确定删除吗？',
            }).then(() => {
                const data = {
                    id: event.currentTarget.dataset.id
                }
                this.del(data)
                instance.close();
            });
        }
    },
    subNumber(e) {
        const data = {
            cid: e.currentTarget.dataset.id
        }
        cart.sub(data, (res) => {
            if (res.code === 0) {
                this.getList()
            }
        })
    },
    addNumber(e) {
        const data = {
            cid: e.currentTarget.dataset.id
        }
        cart.add(data, (res) => {
            if (res.code === 0) {
                this.getList()
            }
        })
    },

    del(data) {
        cart.del(data, (res) => {
            if (res.code === 0) {
                this.getList()
                let selectList = this.data.selectList
                selectList.forEach(function (item, i, array) {
                    if (item === data.id) {
                        array.splice(i, 1)
                    }
                })
                this.setData({
                    selectList: selectList
                })
                wx.setStorageSync("selectList", selectList)
            } else {
                wx.showToast({
                    title: '失败',
                    icon: 'error',
                    duration: 2000
                })
            }
        })
    },

    getUserInfo(e) {
        const that = this
        wx.getUserProfile({
            desc: '获取用户信息，用来快速登录',
            success: (res) => {
                that.toLogin(res)
            }
        })
    },

    toLogin(res) {
        user.wxLogin(res, (res) => {
            if (res.code === 0) {
                wx.setStorageSync('token', res.data.token)
                this.setData({
                    userInfo: res.data.userInfo,
                    login: true
                });
                wx.setStorageSync('login', true)
                wx.setStorageSync('openid', res.data.userInfo.openid)
                wx.setStorageSync('uid', res.data.userInfo.uid)
                wx.setStorageSync("userInfo", res.data.userInfo)
                app.globalData.userInfo = res.data.userInfo;
                app.globalData.token = res.data.token;
                this.getList()
            } else {
                util.showErrorToast('登陆失败')
            }
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
